package com.yzk.aigy.controller;

import com.yzk.aigy.common.Result;
import com.yzk.aigy.exception.MyCustomerException;
import com.yzk.aigy.model.system.SysUser;
import com.yzk.aigy.model.vo.LoginVo;
import com.yzk.aigy.service.SysUserService;
import com.yzk.aigy.utils.JwtHelper;
import com.yzk.aigy.utils.MD5Helper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "登录管理控制器")
@RequiredArgsConstructor
@RequestMapping(value = "/admin/system/index")
public class LoginController {

    private final SysUserService sysUserService;

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    public Result<Map<String, String>> login(@RequestBody LoginVo loginVo) {
        //1.根据username 查询数据
        SysUser sysUser = this.sysUserService.getUserInfoUserName(loginVo.getUsername());

        //2.如果查询为空 给出提示
        if (sysUser == null) throw new MyCustomerException(20001, "用户不存在..");

        //3.比较密码（使用用户输入的密码和数据库密码比较）
        String password = loginVo.getPassword();
        String passwordwithMD5 = MD5Helper.encrypt(password);
        if (!sysUser.getPassword().equals(passwordwithMD5)) {
            throw new MyCustomerException(20001, "密码不正确");
        }

        //4.判断用户是否可用
        if (sysUser.getStatus() == 0) {
            throw new MyCustomerException(20001, "账号被停用..");
        }

        //5.根据userid和username 生成token字符串 再通过map返回
        String token = JwtHelper.createToken(sysUser.getId().toString(), sysUser.getUsername());
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    @ApiOperation("获取用户信息")
    @GetMapping(value = "/info")
    public Result<Map<String, Object>> info(HttpServletRequest request) {
        //a.获取请求头的 token 字符串
        String token = request.getHeader("token");

        //b.从token 字符串获取用户名称 (id)
        String username = JwtHelper.getUsername(token);

        // c.根据用户名称获取用户信息 （a.基本信息  b.菜单权限信息  和 c.按钮权限信息）
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    @ApiOperation("注销")
    @PostMapping("/logout")
    public Result<Object> logout() {
        return Result.ok();
    }

}
